import 'package:flutter/foundation.dart';
import 'package:flutter_reader/db/database_helper.dart';
import 'package:flutter_reader/model/book_history_model/book_history_model.dart';
import 'dart:collection';
import 'package:sqflite/sqflite.dart';

import 'package:flutter/material.dart';

class BookHisProvider with ChangeNotifier {
  DatabaseHelper _databaseHelper = DatabaseHelper();
  List<BookHis> _books;
  int _count = 0;

  UnmodifiableListView<BookHis> get allBooks => UnmodifiableListView(_books);

  void getBookList() {
    final Future<Database> dbFuture = _databaseHelper.initializeDatabase();
    dbFuture.then((database) {
      Future<List<BookHis>> bookListFuture = _databaseHelper.getBookList();
      bookListFuture.then((bookList) {
        this._books = bookList;
        this._count = bookList.length;
        notifyListeners();
      });
    });
  }

  int get count => _count;
  List<BookHis> get books => _books;

  void addBook(BookHis his) async {
    int result;
    if (his.id != null) {
      // result = await _databaseHelper.updateBook(his);
    } else {
      result = await _databaseHelper.insertBook(his);
    }
    if (result != 0) {
      print('Success');
    } else {
      print('Failed');
    }
    notifyListeners();
  }

  void updateBook(BookHis his) async {
    int result;
    if (his.id != null) {
      // result = await _databaseHelper.updateBook(his);
    } else {
      result = await _databaseHelper.updateBook(his);
    }
    if (result != 0) {
      print('Success');
    } else {
      print('Failed');
    }
    notifyListeners();
  }
  //
  // void startCar(BuildContext context, Car car) async {
  //   car.start = !car.start;
  //   int result = await _databaseHelper.updateCar(car);
  //
  //   if (result != 0 && car.start == true) {
  //     _showSnackBar(context, '${car.brand}' +'  '+'${car.type}' + '      ' +'Start');
  //   }
  //   notifyListeners();
  // }
  //
  void deleteBook(BuildContext context, BookHis his) async {
    if (his.id == null) {
      return;
    }

    int result = await _databaseHelper.deleteBook(his.id);
    if (result != 0) {
      debugPrint("删除成功");
    } else {
      debugPrint("删除失败");
    }
    notifyListeners();
  }

}